package com.kyub.spring.gears.web;

import com.kyub.spring.gears.model.PojoDescriptor;
import com.kyub.spring.gears.services.DaoService;
import com.kyub.spring.gears.util.IntrospectionUtils;
import com.kyub.spring.gears.PrjLogger;

import java.beans.PropertyEditorSupport;

/**
 * Builder for dynamicaly created property editors
 */
public class PropertyEditorBuilder {



    public PropertyEditorSupport buildPropertyEditorSupport(final PojoDescriptor pojo, final DaoService dao) {

        final PropertyEditorSupport propertyEditorSupport = new PropertyEditorSupport() {

            public String getAsText() {
                try {
                    PrjLogger.debug(PropertyEditorBuilder.class,"Value: " + getValue().getClass());
                    PrjLogger.debug(PropertyEditorBuilder.class,"Id prop " + pojo.getIdProperty());
                    return String.valueOf(IntrospectionUtils.readPropertyValue(getValue(), pojo.getIdProperty()));
                } catch (Exception e) {
                    PrjLogger.error(PropertyEditorBuilder.class,e.toString());

                    return null;
                }
            }

            public void setAsText(String text) throws IllegalArgumentException {


                setValue(dao.load(text));


            }
        };
        return propertyEditorSupport;
    }


}
